import { Singleton } from "./Singleton";
import { ToastItem } from "./ToastItem";

export class CHint extends Singleton {
	private m_items: ToastItem[] = [];
	private m_itemTimes: number[] = [];
	private m_itemMaxCount: number = 30;
	private m_itemAddInterval: number = 300;
	private m_slideUpHeight: number = 50;
	private m_slideUpTime: number = 300;
	private m_hoverTime: number = 1500;
	private m_fadeOutTime: number = 300;

	constructor() {
		super();
	}

	public showText(text: string, color: string = "#FFFFFF", container: Laya.Sprite = Laya.stage) {
		if (this.m_items.length >= this.m_itemMaxCount) {
			return;
		}

		Laya.loader.load("resources/prefab/toast.lh").then((feb: Laya.Prefab) => {
			let item = feb.create() as ToastItem;
			item.mouseEnabled = false;
			let lab_tex = item.txt;
			lab_tex.text = text;
			lab_tex.color = color;
			item.anchor(0.5, 0.5);
			item.x = container.width * 0.5;
			item.y = container.height * 0.5;
			item.alpha = 0;
			item.zOrder = 9999;
			container.addChild(item);

			if (this.m_items.length == 0) {
				Laya.timer.frameLoop(1, this, this.onLoop);
			}

			this.m_items.push(item);
			this.m_itemTimes.push(this.m_itemTimes.length == 0 ? 0 :
				Math.min(this.m_itemTimes[this.m_itemTimes.length - 1] - this.m_itemAddInterval, 0));
		});
	}

	public clear() {
		for (let i: number = this.m_items.length - 1; i >= 0; i--) {
			if (this.m_items[i].parent) {
				this.m_items[i].parent.removeChild(this.m_items[i]);
			}
			this.m_items[i].destroy();
			this.m_items.splice(i, 1);
		}
		this.m_itemTimes = [];
		Laya.timer.clearAll(this);
	}

	private onLoop() {
		if (this.m_items.length == 0 || this.m_itemTimes.length == 0) {
			Laya.timer.clear(this, this.onLoop);
			return;
		}
		for (let i: number = Math.min(this.m_items.length, this.m_itemTimes.length) - 1; i >= 0; i--) {
			this.m_itemTimes[i] += 1000 / 60;
			let t: number = this.m_itemTimes[i];
			let item = this.m_items[i];
			let container: Laya.Sprite = <Laya.Sprite>item.parent;
			if (!container) {
				this.m_items[i].destroy();
				this.m_items.splice(i, 1);
				this.m_itemTimes.splice(i, 1);
				continue;
			}
			let minY: number = container.height * 0.5 - this.m_slideUpHeight * (this.m_items.length - i) * item.scaleY;
			let vy: number = -this.m_slideUpHeight * item.scaleY / this.m_slideUpTime * 1000 / 60;
			if (t > 0 && item.y > minY) {
				item.y += vy;
			}

			if (t < 0) {
				item.alpha = 0;
			} else if (t < this.m_slideUpTime) {
				item.alpha = t / this.m_slideUpTime;
			} else if (t < this.m_slideUpTime + this.m_hoverTime) {
				item.alpha = 1;
			} else if (t < this.m_slideUpTime + this.m_hoverTime + this.m_fadeOutTime) {
				item.alpha = 1 - (t - this.m_slideUpTime - this.m_hoverTime) / this.m_slideUpTime;
			} else {
				if (this.m_items[i].parent) {
					this.m_items[i].parent.removeChild(this.m_items[i]);
				}
				this.m_items[i].destroy();
				this.m_items.splice(i, 1);
				this.m_itemTimes.splice(i, 1);
			}
		}

	}
}